﻿using System.Buffers;
using System.Net.WebSockets;
using System.Text;

var encoding = new UTF8Encoding(false);
var websocket = new ClientWebSocket();

Console.WriteLine("正在连接...");

await websocket.ConnectAsync(new Uri("ws://127.0.0.1:4040"), CancellationToken.None);

Console.WriteLine("等待数据...");

while (websocket.State == WebSocketState.Open)
{
    var buffer = ArrayPool<byte>.Shared.Rent(1024 * 1024 * 4);

    var reply = await GetWebSocketReply(websocket, buffer, WebSocketMessageType.Text);

    ArrayPool<byte>.Shared.Return(buffer);

    Console.WriteLine(reply);
}

Console.ReadKey();

async ValueTask<string> GetWebSocketReply(ClientWebSocket websocket, byte[] receiveBuffer, WebSocketMessageType messageType)
{
    var sb = new StringBuilder();

    while (true)
    {
        var receiveSegment = new ArraySegment<byte>(receiveBuffer, 0, receiveBuffer.Length);
        var result = await websocket.ReceiveAsync(receiveSegment, CancellationToken.None);

        sb.Append(encoding.GetString(receiveBuffer, 0, result.Count));

        if (result.EndOfMessage)
            break;
    }

    return sb.ToString();
}
